<template>
  <el-card class="filter-bar">
    <div class="filter-content">
      <div class="filter-item">
        <span class="filter-label">时间范围：</span>
        <el-radio-group v-model="timeRange" @change="handleTimeRangeChange">
          <el-radio-button label="week">本周</el-radio-button>
          <el-radio-button label="month">本月</el-radio-button>
          <el-radio-button label="custom">自定义</el-radio-button>
        </el-radio-group>
      </div>

      <div class="filter-item" v-if="timeRange === 'custom'">
        <span class="filter-label">自定义时间：</span>
        <el-date-picker
          v-model="customDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleCustomDateChange"
        />
      </div>

      <div class="filter-item">
        <span class="filter-label">型号筛选：</span>
        <el-select
          v-model="selectedModels"
          multiple
          placeholder="请选择型号"
          style="width: 300px"
          @change="handleModelChange"
        >
          <el-option
            v-for="model in modelList"
            :key="model"
            :label="model"
            :value="model"
          />
        </el-select>
      </div>

      <div class="filter-item">
        <el-button type="primary" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useAnrStore } from '../stores/anr'
import { storeToRefs } from 'pinia'
import { getModelList } from '../api/anr'
import { Refresh } from '@element-plus/icons-vue'

const anrStore = useAnrStore()
const { loading, timeRange, customDateRange, selectedModels } = storeToRefs(anrStore)
const { setTimeRange, setCustomDateRange, setSelectedModels, refreshAllData } = anrStore

const modelList = ref([])

onMounted(async () => {
  try {
    const models = await getModelList()
    const unique = new Set()
    modelList.value = (models || [])
      .filter(m => !!m && String(m).trim().length > 0)
      .filter(m => (unique.has(m) ? false : (unique.add(m), true)))
      .sort()
  } catch (error) {
    console.error('获取型号列表失败:', error)
  }
})

const handleTimeRangeChange = (value) => { setTimeRange(value) }
const handleCustomDateChange = (value) => { setCustomDateRange(value) }
const handleModelChange = (value) => { setSelectedModels(value) }
const refreshData = () => { refreshAllData() }
</script>

<style scoped>
.filter-bar { margin-bottom: 20px; }
.filter-content { display: flex; align-items: center; gap: 20px; flex-wrap: wrap; }
.filter-item { display: flex; align-items: center; gap: 8px; }
.filter-label { font-weight: 500; color: #606266; white-space: nowrap; }
</style>
